package com.ruoyi.socket.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.bussiness.domain.TContractCoin;
import com.ruoyi.bussiness.domain.TCurrencySymbol;
import com.ruoyi.bussiness.domain.TSecondCoinConfig;
import com.ruoyi.bussiness.service.ITContractCoinService;
import com.ruoyi.bussiness.service.ITCurrencySymbolService;
import com.ruoyi.bussiness.service.ITSecondCoinConfigService;
import com.ruoyi.common.service.FinancialDataService;
import com.ruoyi.common.utils.AllTickApiUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.socket.manager.WebSocketUserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URISyntaxException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * energy 能源
 */
@Slf4j
@EnableScheduling
@Component
public class MarketThreadEnergy {

    @Resource
    private ITSecondCoinConfigService secondCoinConfigService;
    @Resource
    private ITContractCoinService contractCoinService;
    @Resource
    private ITCurrencySymbolService tCurrencySymbolService;
    @Resource
    private WebSocketUserManager webSocketUserManager;
    @Resource
    private FinancialDataService financialDataService;

    private static final Set<String> coins = new HashSet<>();

    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void getSecondCoins() {
        //秒合约Crude原油
        TSecondCoinConfig tSecondCoinConfig = new TSecondCoinConfig();
        tSecondCoinConfig.setMarket("energy");
        tSecondCoinConfig.setStatus(1L);
        List<TSecondCoinConfig> tSecondCoinConfigs = secondCoinConfigService.selectTSecondCoinConfigList(tSecondCoinConfig);
        for (TSecondCoinConfig secondCoinConfig : tSecondCoinConfigs) {
            coins.add(secondCoinConfig.getCoin().toUpperCase());
        }
        //U本位
        TContractCoin tContractCoin = new TContractCoin();
        tContractCoin.setEnable(0L);
        tContractCoin.setMarket("energy");
        List<TContractCoin> tContractCoins = contractCoinService.selectTContractCoinList(tContractCoin);
        for (TContractCoin contractCoin : tContractCoins) {
            coins.add(contractCoin.getCoin().toUpperCase());
        }
        //币币
        TCurrencySymbol tCurrencySymbol = new TCurrencySymbol();
        tCurrencySymbol.setEnable("1");
        tCurrencySymbol.setMarket("energy");
        List<TCurrencySymbol> tCurrencySymbols = tCurrencySymbolService.selectTCurrencySymbolList(tCurrencySymbol);
        for (TCurrencySymbol currencySymbol : tCurrencySymbols) {
            coins.add(currencySymbol.getCoin().toUpperCase());
        }
        log.info(JSONObject.toJSONString(coins));
    }

    @Async
    @Scheduled(cron = "*/15 * * * * ?")
    public void marketThreadRun() throws URISyntaxException {
        if (isOffDay()) {
            log.info("星期六星期日 不查");
            return;
        }
        // 商品数据已禁用，不再请求外部API，直接使用模拟数据
        log.info("商品数据API已禁用，使用模拟数据");
        
        for (String coinStr : coins) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 直接使用模拟数据，不再请求外部API
                        String mockResult = generateMockEnergyData(coinStr);
                        if (StringUtils.isNotEmpty(mockResult)) {
                            log.info("使用模拟商品数据: {}", coinStr);
                            webSocketUserManager.crudeKlineSendMeg(mockResult, coinStr);
                            webSocketUserManager.metalDETAILSendMeg(mockResult, coinStr);
                        }
                        
                    } catch (Exception e) {
                        log.error("商品模拟数据生成失败: {}, 错误: {}", coinStr, e.getMessage());
                    }
                }
            });
            thread.start();
        }
    }

    private boolean isOffDay() {
        LocalDate today = LocalDate.now();
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
            log.info("星期六星期日 不查");
            return true;
        }
        return false;
    }

    /**
     * 生成模拟能源数据（备用方案）
     */
    private String generateMockEnergyData(String symbol) {
        double basePrice = getBaseEnergyPrice(symbol);
        double randomChange = (Math.random() - 0.5) * 0.02; // ±1%随机变化
        double currentPrice = basePrice * (1 + randomChange);
        
        // 使用AllTickApiUtil生成标准的fx678格式数据
        return AllTickApiUtil.createFx678ArrayFormat(symbol, 0, 0, 0, 0, currentPrice);
    }
    
    /**
     * 获取基础能源价格
     */
    private double getBaseEnergyPrice(String symbol) {
        switch (symbol.toUpperCase()) {
            case "OIL":
            case "CRUDE":
            case "USOIL":
                return 80.00;
            case "GAS":
            case "NGAS":
                return 3.00;
            case "BRENT":
            case "UKOIL":
                return 82.00;
            case "HEATING":
                return 2.50;
            default:
                return 50.00;
        }
    }

}
